#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : book.py
@Author  : lepal
@Time    : 2024-02-29 17:16
"""
from flask import jsonify
from sqlalchemy import or_

# from flask import Blueprint
from app.libs.RedPrint import RedPrint
from app.models.book import Book
from app.validators.forms import BookSearchForm

# book = Blueprint('book', '__main__')
api = RedPrint('book')

# @app.route('/'), 因为app核心对象在入口文件中，如果把入口文件的app对象在当前导入会导致循环导入，所以使用蓝图解决
@api.route('/get')
def get_book():
    return 'get book'



# 根据q字段作为关键词搜索书籍
@api.route('/search')
def search():
    form = BookSearchForm().validate_for_api()
    print('form',form)
    q = '%' + form.q.data + '%'
    # book = Book()
    # 元类 ORM

    books = Book.query.filter(or_(Book.title.like(q), Book.publisher.like(q))).all()

    # 过滤掉某个属性不返回给前端，（这里就牵扯到了  book模型里面的 __init__ 和 keys方法的调整）
    books = [book.hide('summary','binding') for book in books]
    #  如果不使用hide方法其实也可以使用model_to_dict 方法
    # books = [book.model_to_dict(exclude=['summary','binding']) for book in books]
    return jsonify(books)
